<template>
  <div class="purchase-container">
    <!-- 筛选区域 -->
    <el-card class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams">
        <el-form-item label="制单时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            type="daterange"
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.productName" maxlength="40" placeholder="请输入商品名称" show-word-limit />
        </el-form-item>
        <el-form-item label="单据编号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入单据编号" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="queryParams.supplier" filterable placeholder="请选择供应商">
            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="queryParams.logisticsNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="仓库门店">
          <el-select v-model="queryParams.warehouse" filterable placeholder="请选择仓库门店">
            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="制单人">
          <el-input v-model="queryParams.creator" placeholder="请输入制单人" />
        </el-form-item>
        <el-form-item label="单据类型">
          <el-select v-model="queryParams.orderType" placeholder="请选择单据类型">
            <el-option label="全部" value="" />
            <el-option label="普通采购单" value="normal" />
            <el-option label="销售集采单" value="sales" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">筛选</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 状态标签页和表格 -->
    <el-card class="table-container">
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="待审核" name="pending" />
        <el-tab-pane label="待入库" name="toStorage" />
        <el-tab-pane label="已驳回" name="rejected" />
        <el-tab-pane label="已作废" name="cancelled" />
        <el-tab-pane label="已完成" name="completed" />
      </el-tabs>

      <el-table border :data="tableData" style="width: 100%">
        <el-table-column label="单据编号" prop="orderNo" />
        <el-table-column label="单据类型" prop="orderTypeLabel" />
        <el-table-column label="商品" prop="productName" />
        <el-table-column label="供应商" prop="supplierLabel" />
        <el-table-column label="入库仓库/门店" prop="warehouseLabel" />
        <el-table-column label="状态" prop="status" />
        <el-table-column label="物流单号" prop="logisticsNo" />
        <el-table-column label="采购数量" prop="quantity" />
        <el-table-column label="制单时间" prop="createTime" />
        <el-table-column label="制单人" prop="creator" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === '待审核'" type="text" @click="handleAudit(scope.row)">审核</el-button>
            <el-button v-if="scope.row.status === '待入库'" type="text" @click="handleStorage(scope.row)">入库</el-button>
            <el-button v-if="scope.row.status === '已驳回'" type="text" @click="handleViewReason(scope.row)">查看原因</el-button>
            <el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page.sync="pagination.currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 入库确认弹窗 -->
    <el-dialog title="入库确认" :visible.sync="storageDialog.visible" width="500px">
      <el-form :model="storageDialog.form">
        <el-form-item label="选择仓库">
          <el-select v-model="storageDialog.form.warehouse" placeholder="请选择入库仓库">
            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="storageDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmStorage">确认</el-button>
      </div>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="订单审核" :visible.sync="auditDialog.visible" width="500px">
      <div class="audit-info">
        <p><strong>单据编号：</strong>{{ auditDialog.currentRow ? auditDialog.currentRow.orderNo : '' }}</p>
        <p><strong>供应商：</strong>{{ auditDialog.currentRow ? auditDialog.currentRow.supplierLabel : '' }}</p>
        <p><strong>采购数量：</strong>{{ auditDialog.currentRow ? auditDialog.currentRow.quantity : '' }}</p>
      </div>
      <el-form v-if="auditDialog.action === 'reject'" :model="auditDialog.form" :rules="auditDialog.rules">
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input
            v-model="auditDialog.form.rejectReason"
            placeholder="请输入驳回原因"
            :rows="3"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialog.visible = false">取消</el-button>
        <el-button type="success" @click="confirmAudit('pass')">审核通过</el-button>
        <el-button type="danger" @click="confirmAudit('reject')">驳回</el-button>
      </div>
    </el-dialog>

    <!-- 驳回原因查看弹窗 -->
    <el-dialog title="驳回原因" :visible.sync="reasonDialog.visible" width="500px">
      <div class="reason-info">
        <p><strong>单据编号：</strong>{{ reasonDialog.currentRow ? reasonDialog.currentRow.orderNo : '' }}</p>
        <p><strong>供应商：</strong>{{ reasonDialog.currentRow ? reasonDialog.currentRow.supplierLabel : '' }}</p>
        <p><strong>驳回原因：</strong></p>
        <div class="reason-content">{{ reasonDialog.currentRow ? reasonDialog.currentRow.rejectReason : '' }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reasonDialog.visible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="detailDialog.visible" width="700px">
      <div v-if="detailDialog.currentRow" class="detail-info">
        <el-descriptions border :column="2">
          <el-descriptions-item label="单据编号">{{ detailDialog.currentRow.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="单据类型">{{ detailDialog.currentRow.orderTypeLabel }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ detailDialog.currentRow.supplierLabel }}</el-descriptions-item>
          <el-descriptions-item label="入库仓库/门店">{{ detailDialog.currentRow.warehouseLabel }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detailDialog.currentRow.status }}</el-descriptions-item>
          <el-descriptions-item label="物流单号">{{ detailDialog.currentRow.logisticsNo }}</el-descriptions-item>
          <el-descriptions-item label="采购数量">{{ detailDialog.currentRow.quantity }}</el-descriptions-item>
          <el-descriptions-item label="制单时间">{{ detailDialog.currentRow.createTime }}</el-descriptions-item>
          <el-descriptions-item label="制单人">{{ detailDialog.currentRow.creator }}</el-descriptions-item>
          <el-descriptions-item v-if="detailDialog.currentRow.productName" label="商品名称">
            {{ detailDialog.currentRow.productName }}
          </el-descriptions-item>
          <el-descriptions-item v-if="detailDialog.currentRow.rejectReason" label="驳回原因" :span="2">
            {{ detailDialog.currentRow.rejectReason }}
          </el-descriptions-item>
          <el-descriptions-item v-if="detailDialog.currentRow.remarks" label="备注" :span="2">
            {{ detailDialog.currentRow.remarks }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Purchase',

    data() {
      return {
        activeTab: 'all',
        queryParams: {
          dateRange: [],
          productName: '',
          orderNo: '',
          supplier: '',
          logisticsNo: '',
          warehouse: '',
          creator: '',
          orderType: '',
        },
        pickerOptions: {
          shortcuts: [
            {
              text: '今天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                picker.$emit('pick', [start, end])
              },
            },
            {
              text: '最近7天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              },
            },
            {
              text: '最近30天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              },
            },
          ],
        },
        supplierOptions: [
          { value: 'SUP_001', label: '京东商城供应商' },
          { value: 'SUP_002', label: '天猫优选供应商' },
          { value: 'SUP_003', label: '苏宁易购供应商' },
          { value: 'SUP_004', label: '小米商城供应商' },
        ],
        warehouseOptions: [
          { value: 'WH_001', label: '北京中心仓' },
          { value: 'WH_002', label: '上海配送中心' },
          { value: 'WH_003', label: '广州物流仓' },
          { value: 'WH_004', label: '深圳分仓' },
        ],
        tableData: [], // 当前页显示的数据
        originalTableData: [], // 存储所有原始数据
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        storageDialog: {
          visible: false,
          form: {
            warehouse: '',
          },
          currentRow: null,
        },
        // 新增审核弹窗数据
        auditDialog: {
          visible: false,
          action: '', // 'pass' 或 'reject'
          currentRow: null,
          form: {
            rejectReason: '',
          },
          rules: {
            rejectReason: [
              { required: true, message: '请输入驳回原因', trigger: 'blur' },
              { min: 5, message: '驳回原因不能少于5个字符', trigger: 'blur' }
            ]
          }
        },
        // 新增驳回原因查看弹窗数据
        reasonDialog: {
          visible: false,
          currentRow: null,
        },
        // 新增详情弹窗数据
        detailDialog: {
          visible: false,
          currentRow: null,
        },
      }
    },

    created() {
      this.initTableData()
      // 初始化加载仓库数据
      this.loadWarehouseOptions()
    },

    mounted() {
      // 监听storage事件，当其他页面更新了localStorage时刷新数据
      window.addEventListener('storage', (e) => {
        if (e.key === 'purchaseTableData') {
          this.initTableData()
        }
      })

      // 添加对storageUpdated事件的监听，用于接收仓库数据更新的通知
      window.addEventListener('storageUpdated', (e) => {
        if (e.detail && e.detail.key === 'warehouseTableData') {
          this.loadWarehouseOptions()
        }
      })
    },

    beforeDestroy() {
      // 移除事件监听
      window.removeEventListener('storage', this.handleStorageChange)
      // 移除仓库数据更新事件监听
      window.removeEventListener('storageUpdated', this.handleStorageUpdated)
    },

    methods: {
      loadWarehouseOptions() {
      const warehouseData = localStorage.getItem('warehouseTableData')
      if (warehouseData) {
        const warehouses = JSON.parse(warehouseData)
        this.warehouseOptions = warehouses.map(warehouse => ({
          value: `WH_${warehouse.id}`,
          label: warehouse.name
        }))
      } else {
        // 如果没有数据，使用默认值
        this.warehouseOptions = [
          { value: 'WH_001', label: '北京中心仓' },
          { value: 'WH_002', label: '上海配送中心' },
          { value: 'WH_003', label: '广州物流仓' },
          { value: 'WH_004', label: '深圳分仓' },
        ]
      }
    },
      initTableData() {
        const storedData = localStorage.getItem('purchaseTableData')
        if (storedData) {
          this.originalTableData = JSON.parse(storedData)
        } else {
          const data = []
          const statusList = ['待审核', '待入库', '已驳回', '已作废', '已完成']
          const orderTypes = [
            { label: '普通采购单', value: 'normal' },
            { label: '销售集采单', value: 'sales' },
          ]
          const creators = ['张三', '李四', '王五', '赵六']

          for (let i = 1; i <= 20; i++) {
            const orderNo = `PO${new Date().getFullYear()}${String(i).padStart(6, '0')}`
            const selectedOrderType = orderTypes[Math.floor(Math.random() * orderTypes.length)]
            const selectedSupplier = this.supplierOptions[Math.floor(Math.random() * this.supplierOptions.length)]
            const selectedWarehouse = this.warehouseOptions[Math.floor(Math.random() * this.warehouseOptions.length)]

            data.push({
              orderNo,
              orderType: selectedOrderType.value,
              orderTypeLabel: selectedOrderType.label,
              supplier: selectedSupplier.value,
              supplierLabel: selectedSupplier.label,
              warehouse: selectedWarehouse.value,
              warehouseLabel: selectedWarehouse.label,
              status: statusList[Math.floor(Math.random() * statusList.length)],
              logisticsNo: `LG${Math.random().toString(36).substr(2, 8).toUpperCase()}`,
              quantity: Math.floor(Math.random() * 500) + 50,
              createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toLocaleString('zh-CN', {
                hour12: false,
              }),
              creator: creators[Math.floor(Math.random() * creators.length)],
            })
          }
          this.originalTableData = data
          this.saveTableData() // 保存初始模拟数据
        }
        this.handleQuery()
      },

      saveTableData() {
        localStorage.setItem('purchaseTableData', JSON.stringify(this.originalTableData))
      },

      handleQuery() {
        let filteredData = [...this.originalTableData]

        // 按日期范围筛选
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
          const startDate = this.queryParams.dateRange[0]
          const endDate = this.queryParams.dateRange[1]
          filteredData = filteredData.filter((item) => {
            const createTime = new Date(item.createTime)
            return createTime >= startDate && createTime <= endDate
          })
        }

        // 其他筛选条件
        if (this.queryParams.productName) {
          filteredData = filteredData.filter((item) => item.productName && item.productName.includes(this.queryParams.productName))
        }

        if (this.queryParams.orderNo) {
          filteredData = filteredData.filter((item) => item.orderNo.includes(this.queryParams.orderNo))
        }

        if (this.queryParams.supplier) {
          filteredData = filteredData.filter((item) => item.supplier === this.queryParams.supplier)
        }

        if (this.queryParams.warehouse) {
          filteredData = filteredData.filter((item) => item.warehouse === this.queryParams.warehouse)
        }

        if (this.queryParams.orderType) {
          filteredData = filteredData.filter((item) => item.orderType === this.queryParams.orderType)
        }

        if (this.queryParams.logisticsNo) {
          filteredData = filteredData.filter((item) => item.logisticsNo.includes(this.queryParams.logisticsNo))
        }

        if (this.queryParams.creator) {
          filteredData = filteredData.filter((item) => item.creator.includes(this.queryParams.creator))
        }

        // 状态标签筛选
        if (this.activeTab !== 'all') {
          const statusMap = {
            pending: '待审核',
            toStorage: '待入库',
            rejected: '已驳回',
            cancelled: '已作废',
            completed: '已完成',
          }
          filteredData = filteredData.filter((item) => item.status === statusMap[this.activeTab])
        }

        this.pagination.total = filteredData.length
        const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
        const end = start + this.pagination.pageSize
        this.tableData = filteredData.slice(start, end)
      },

      resetQuery() {
        this.queryParams = {
          dateRange: [],
          productName: '',
          orderNo: '',
          supplier: '',
          logisticsNo: '',
          warehouse: '',
          creator: '',
          orderType: '',
        }
        this.pagination.currentPage = 1
        this.handleQuery()
      },

      handleTabClick() {
        this.pagination.currentPage = 1
        this.handleQuery()
      },

      handleSizeChange(val) {
        this.pagination.pageSize = val
        this.handleQuery()
      },

      handleCurrentChange(val) {
        this.pagination.currentPage = val
        this.handleQuery()
      },

      handleStorage(row) {
        this.storageDialog.visible = true
        this.storageDialog.form.warehouse = row.warehouse
        this.storageDialog.currentRow = row
      },

      confirmStorage() {
        const item = this.storageDialog.currentRow
        if (item && this.storageDialog.form.warehouse) {
          const selectedWarehouseOption = this.warehouseOptions.find(
            (option) => option.value === this.storageDialog.form.warehouse
          )

          item.warehouse = this.storageDialog.form.warehouse
          item.warehouseLabel = selectedWarehouseOption ? selectedWarehouseOption.label : ''
          item.status = '已完成' // 或者其他表示已入库的状态，如 '待调拨' 或 '库存中'
          this.saveTableData()
          this.handleQuery() // 刷新表格
          this.storageDialog.visible = false
          this.$message.success('入库操作成功！')

          // --- 新增：将入库商品信息添加到 productAllocationData ---
          const allocationData = localStorage.getItem('productAllocationData')
          let allocations = allocationData ? JSON.parse(allocationData) : []

          const newAllocationEntry = {
            id: `ALLOC-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
            purchaseOrderNo: item.orderNo,
            productName: item.productName, // 确保item中有productName
            logisticsNo: item.logisticsNo,
            initialQuantity: item.quantity,
            currentQuantity: item.quantity,
            warehouseId: item.warehouse,
            warehouseLabel: item.warehouseLabel,
            storageTimestamp: new Date().toLocaleString('zh-CN', { hour12: false }),
            status: '库存中', // 初始状态
            creator: item.creator, // 可以继承制单人
            supplierLabel: item.supplierLabel, // 可能用于退货
          }
          allocations.push(newAllocationEntry)
          localStorage.setItem('productAllocationData', JSON.stringify(allocations))
          // 触发一个事件，以便其他页面（如商品调拨页面）可以监听到数据变化
          window.dispatchEvent(new CustomEvent('storageUpdated', { detail: { key: 'productAllocationData' } }));
          // --- 结束新增 ---

        } else {
          this.$message.error('请选择入库仓库')
        }
      },

      handleAudit(row) {
        this.auditDialog.visible = true;
        this.auditDialog.currentRow = row;
        this.auditDialog.action = '';
        this.auditDialog.form.rejectReason = '';
      },

      // 确认审核
      confirmAudit(action) {
        this.auditDialog.action = action;

        if (action === 'reject') {
          // 如果是驳回，需要验证驳回原因
          if (!this.auditDialog.form.rejectReason) {
            this.$message.warning('请输入驳回原因');
            return;
          }

          if (this.auditDialog.form.rejectReason.length < 5) {
            this.$message.warning('驳回原因不能少于5个字符');
            return;
          }
        }

        // 更新状态
        const index = this.originalTableData.findIndex((item) => item.orderNo === this.auditDialog.currentRow.orderNo);
        if (index !== -1) {
          if (action === 'pass') {
            this.originalTableData[index].status = '待入库';
            this.$message.success('审核通过');
          } else {
            this.originalTableData[index].status = '已驳回';
            this.originalTableData[index].rejectReason = this.auditDialog.form.rejectReason;
            this.$message.success('已驳回订单');
          }
        }

        this.saveTableData(); // 保存更改到localStorage
        this.auditDialog.visible = false;
        this.handleQuery(); // 重新查询以刷新表格
      },

      // 处理查看驳回原因按钮点击
      handleViewReason(row) {
        this.reasonDialog.visible = true;
        this.reasonDialog.currentRow = row;
      },

      // 处理详情按钮点击
      handleDetail(row) {
        this.detailDialog.visible = true;
        this.detailDialog.currentRow = row;
      },
    },
  }
</script>

<style lang="scss" scoped>
  .purchase-container {
    padding: 20px;

    .filter-container {
      margin-bottom: 20px;
    }

    .table-container {
      margin-top: 20px;
    }

    .audit-info, .reason-info, .detail-info {
      margin-bottom: 20px;
    }

    .reason-content {
      padding: 10px;
      background-color: #f8f8f8;
      border-radius: 4px;
      min-height: 60px;
    }
  }
</style>
